package app

import (
	"fmt"
	"net"
	"strings"

	x "gitcode.com/shexk/xframe/plugin"
)

type CommandCenter struct {
	CurrentUsePluginName string
}

func NewCC() *CommandCenter {
	return &CommandCenter{}
}

// 发送者和接收者的值为json格式,格式如下：
// {"Type":"Plugin/Topic/Service/xxx","Name"="xxx”}
func (cc *CommandCenter) ProcessCommand(addr *net.UDPAddr, data []byte, datasize int) {
	GetLog().WriteLog(Log_Debug, "Receive From CommandCenter:", string(data[:datasize]))
	cmd := string(data[:datasize])
	vf := strings.Fields(cmd)
	switch vf[0] {
	case "ls":
		if len(vf) > 1 {
			switch vf[1] {
			case "plugin":
				for k := range GetApp().pluginmng.Plugins {
					GetApp().udp.SendTo(addr, []byte(k), len(k))
				}
			case "topic":
				for k := range GetApp().topic.TL {
					GetApp().udp.SendTo(addr, []byte(k), len(k))
					ss := GetApp().topic.TL[k]
					for uc := range ss.PL {
						GetApp().udp.SendTo(addr, []byte("{"+uc+"}"), len(uc)+2)
					}
				}
			default:
				vp := string("ls format error,eg:ls plugin or ls ls topic")
				GetApp().udp.SendTo(addr, []byte(vp), len(vp))
			}
		} else {
			vp := string("ls format error,eg:ls plugin or ls ls topic")
			GetApp().udp.SendTo(addr, []byte(vp), len(vp))
		}

	case "use":
		if len(vf) > 1 {
			fmt.Println("Plugin:", vf[1])
			if _, ok := GetApp().pluginmng.Plugins[vf[1]]; ok {
				cc.CurrentUsePluginName = vf[1]
				res := "useing " + vf[1]
				GetApp().udp.SendTo(addr, []byte(res), len(res))
			} else {
				cc.CurrentUsePluginName = ""
				GetApp().udp.SendTo(addr, []byte("close use"), 9)
			}
		} else {
			cc.CurrentUsePluginName = ""
			GetApp().udp.SendTo(addr, []byte("close use"), 9)
		}
	default:
		if cc.CurrentUsePluginName != "" { //将从UDP接收到的数据传递到插件内执行

			v := x.Object{Type: x.Type_Plugin, Name: cc.CurrentUsePluginName}
			ss := x.PluginMsg{ID: x.GetMessageID(), Cmd: x.Command_TransPlugin,
				Sender:   x.Object{Type: x.Type_Service, Name: "CommandCenter"},
				Receiver: []x.Object{v},
				Option:   addr.String(),
				Data:     []byte(cmd)}
			GetApp().appobj.DataBus <- &ss
		} else {
			GetApp().udp.SendTo(addr, []byte("none object command"), 19)
		}
	}
}
